part of 'view.dart';

class CountDownProvider extends ChangeNotifier {
  late int timeMax;
  late int interval;
  late int _time;
  Timer? _timer;
  bool _isFirst = true;

  int get currentTime => _time;

  bool get isFinish => _time == timeMax;

  bool get isFirst => _isFirst;

  CountDownProvider({int timeMax = 60, int interval = 1}) {
    init(timeMax: timeMax, interval: interval);
  }

  init({int timeMax = 60, int interval = 1}) {
    this.timeMax = timeMax;
    this.interval = interval;
    _time = timeMax;
  }

  void startCountDown() {
    _isFirst = false;
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
    _time--;
    notifyListeners();
    _timer = Timer.periodic(Duration(seconds: interval), (timer) {
      if (timer.tick == timeMax) {
        _time = timeMax;
        timer.cancel();
      } else {
        _time--;
      }
      if (_time < 0) {
        _time = 0;
        timer.cancel();
      }
      notifyListeners();
    });
  }

  void cancel() {
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
  }
}
